# role_dao.py
import datetime

from sqlalchemy.orm import Session
from ..do.role_do import RoleModel


def getRole(db: Session, role_id: str):
    return db.query(RoleModel).filter(RoleModel.id == role_id).first()


def getRoles(db: Session, skip: int = 0, limit: int = 100, role_name: str = None, status: str = None,
             role_id: str = None, remark: str = None, create_time_start: str = None, create_time_end: str = None):
    query = db.query(RoleModel)
    if role_name:
        query = query.filter(RoleModel.name.like(f'%{role_name}%'))
    if status:
        query = query.filter(RoleModel.status == status)
    if role_id:
        query = query.filter(RoleModel.id == role_id)
    if remark:
        query = query.filter(RoleModel.remark.like(f'%{remark}%'))
    try:
        # 处理 GMT 格式日期：'Thu,+30+Jan+2025+16:00:00+GMT'
        # 先替换 + 为空格，然后解析
        gmt_date = create_time_start.replace('+', ' ')
        start_date = datetime.datetime.strptime(gmt_date, '%a, %d %b %Y %H:%M:%S GMT')
        query = query.filter(RoleModel.createTime >= start_date)
    except Exception as e:
        print(str(e))
        # 如果 GMT 格式解析失败，尝试其他格式
        try:
            # 尝试 YYYY-MM-DD 格式
            start_date = datetime.datetime.strptime(create_time_start, '%Y-%m-%d')
            query = query.filter(RoleModel.createTime >= start_date)
        except ValueError:
            pass  # 如果所有格式都不正确，忽略此条件
    if create_time_end:
        try:
            # 处理 GMT 格式日期
            gmt_date = create_time_end.replace('+', ' ')
            end_date = datetime.datetime.strptime(gmt_date, '%a, %d %b %Y %H:%M:%S GMT') + datetime.timedelta(days=1)
            query = query.filter(RoleModel.createTime < end_date)
        except Exception as e:
            print(str(e))
            try:
                end_date = datetime.datetime.strptime(create_time_end, '%Y-%m-%d') + datetime.timedelta(days=1)
                query = query.filter(RoleModel.createTime < end_date)
            except ValueError:
                pass  # 如果所有格式都不正确，忽略此条件
    return query.offset(skip).limit(limit).all()


def get_roles_count(db: Session, role_name: str = None, status: str = None,
                   role_id: str = None, remark: str = None, create_time_start: str = None, create_time_end: str = None):
    query = db.query(RoleModel)
    if role_name:
        query = query.filter(RoleModel.name.like(f'%{role_name}%'))
    if status:
        query = query.filter(RoleModel.status == status)
    if role_id:
        query = query.filter(RoleModel.id == role_id)
    if remark:
        query = query.filter(RoleModel.remark.like(f'%{remark}%'))
    if create_time_start:
        from datetime import datetime
        try:
            start_date = datetime.strptime(create_time_start, '%Y-%m-%d')
            query = query.filter(RoleModel.createTime >= start_date)
        except ValueError:
            pass  # 如果日期格式不正确，忽略此条件
    if create_time_end:
        from datetime import datetime, timedelta
        try:
            end_date = datetime.strptime(create_time_end, '%Y-%m-%d') + timedelta(days=1)
            query = query.filter(RoleModel.createTime < end_date)
        except ValueError:
            pass  # 如果日期格式不正确，忽略此条件
    return query.count()


def createRole(db: Session, role):
    roleModel = RoleModel(**role)
    db.add(roleModel)
    db.commit()
    db.refresh(roleModel)
    return roleModel


def updateRole(db: Session, role_id: str, role):
    roleModel = getRole(db, role_id)
    if roleModel is None:
        return None
    for key, value in role.items():
        setattr(roleModel, key, value)
    db.commit()
    db.refresh(roleModel)
    return roleModel


def deleteRole(db: Session, role_id: str):
    roleModel = getRole(db, role_id)
    if roleModel is None:
        return False
    db.delete(roleModel)
    db.commit()
    return True

def get_all_roles(db: Session):
    return db.query(RoleModel).all()